package com.ld;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.junit.Test;

public class FlowController {

	public void applyUpgrade() {
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		RuntimeService rt = processEngine.getRuntimeService();
		for (int i = 1001; i < 1005; i++) {
			processEngine.getIdentityService().setAuthenticatedUserId(i + "");
			ProcessInstance instance = rt
					.startProcessInstanceByKey("upgradeApply2");
			System.out.println(instance.getId() + ":"
					+ instance.getDeploymentId());
			System.out.println(instance.getProcessDefinitionKey() + ","
					+ instance.getProcessDefinitionId() + ","
					+ instance.getActivityId());
		}
	}

	// @Test
	public void startProgress() {
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		RuntimeService rt = processEngine.getRuntimeService();
		processEngine.getIdentityService().setAuthenticatedUserId("kermit");
		ProcessInstance instance = rt
				.startProcessInstanceById("test-parallel:1:106626");
	}

//	 @Test
	public void listTaskForDeal() {
		// ProcessEngine processEngine
		// =ProcessEngines.getDefaultProcessEngine();
		ProcessEngine processEngine = ProcessEngineConfiguration
				.createProcessEngineConfigurationFromResource(
						"activiti.cfg.xml").buildProcessEngine();
//		List<Task> tasks = processEngine.getTaskService().createTaskQuery()
//				.taskAssignee("gonzo").list();
		List<String> candis = new ArrayList<String>();
		candis.add("sales");
		List<Task> tasks = processEngine.getTaskService().createTaskQuery()
				.taskCandidateGroupIn(candis).list();
		for (Task tmp : tasks) {
			System.out.println(tmp.getId() + ":" + tmp.getProcessInstanceId()
					+ ":" + tmp.getAssignee() + ":" + tmp.getName() + ":"
					+ tmp.getDescription());
		}
	}

	 @Test
	public void completeTask() {
		String taskId = "119187";
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		List<Task> tasks = processEngine.getTaskService().createTaskQuery()
				.taskName("t2").processInstanceId("72501").list();
		int count = 0;
		int totalCount = 0;
		String passflag = "yes";
		for (Task tmp : tasks) {

			String tmpCount = processEngine.getTaskService().getVariable(
					tmp.getId(), "passCount")
					+ "";
			String tmpTotal = processEngine.getTaskService().getVariable(
					tmp.getId(), "totalCount")
					+ "";
			if (tmpCount != null && !tmpCount.trim().equals("")) {
				count = Integer.parseInt(tmpCount);
			}
			if (tmpTotal != null && !tmpTotal.trim().equals("")) {
				totalCount = Integer.parseInt(tmpTotal);
			}
			System.out.println(tmp.getId() + "var = " + passflag);
			if (passflag.equals("yes")) {
				count++;
			}
			totalCount++;
		}
		Map<String, Object> vars = new HashMap<String, Object>();
		vars.put("passCount", count);
		vars.put("totalCount", totalCount);
		processEngine.getTaskService().complete(taskId, vars);
	}

	public void completeTaskByName() {
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		TaskService ts = processEngine.getTaskService();
		List<Task> tasks = ts.createTaskQuery().deploymentId("5001")
				.taskName("升级申请").list();
		for (Task tmp : tasks) {
			System.out.println(tmp.getId() + ":" + tmp.getProcessInstanceId()
					+ ":" + tmp.getAssignee() + ":" + tmp.getName());
			ts.complete(tmp.getId());
		}
	}

//	@Test
	public void queryProcessDefinition() {
		// 获取流程引擎对象
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		// 获取仓库服务对象，使用版本的升序排序，查询列表
		// List<ProcessDefinition>
		// processDefinitions=processEngine.getRepositoryService().createProcessDefinitionQuery()
		// .orderByProcessDefinitionVersion()
		// .asc().list();
		// //遍历
		// for(ProcessDefinition processDefinition:processDefinitions){
		// System.out.println("Id:"+processDefinition.getId());
		// System.out.println("DeploymentId:"+processDefinition.getDeploymentId());
		// System.out.println("Name:"+processDefinition.getName());
		// System.out.println("Key:"+processDefinition.getKey());
		// System.out.println("Version:"+processDefinition.getVersion());
		// System.out.println("DiagramResourceName:"+processDefinition.getDiagramResourceName());
		// System.out.println("****************************************************************");
		// }

		ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) processEngine
				.getRepositoryService().getProcessDefinition(
						"test-parallel:1:106626");
		List<ActivityImpl> aci = processDefinition.getActivities();
		System.out.println(processDefinition);
		System.out.println("==================");
		for(ActivityImpl tmp : aci){
			System.out.println(tmp.getProperty("name")+":"+tmp.getProperty("multiInstance"));
		}
		
	}

	// 查看流程状态（判断流程是正在执行还是已经结束）
	public void queryProcessState() {
		String processInstanceId = "41771";
		// 获取流程引擎对象
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		// 通过流程实例id查询流程实例
		ProcessInstance pi = processEngine.getRuntimeService()
				.createProcessInstanceQuery()
				.processInstanceId(processInstanceId).singleResult();
		if (pi != null) {
			System.out.println("当前流程在" + pi.getActivityId());
		} else {
			System.out.println("流程已结束！");
		}
	}

	// 查询历史任务
	public void queryHistoryTask() {
		// 历史任务办理人
		// 获取流程引擎对象
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		// 使用办理人查询流程实例
		List<HistoricTaskInstance> list = processEngine.getHistoryService()
				.createHistoricTaskInstanceQuery()
				// .taskAssignee(taskAssignee)
				.processInstanceId("43749").list();
		if (list != null && list.size() > 0) {
			for (HistoricTaskInstance task : list) {
				System.out.println("================");
				System.out.println("任务id：" + task.getId());
				System.out.println("流程实例ID:" + task.getProcessInstanceId());
				System.out.println("任务办理人：" + task.getAssignee());
				System.out.println("任务名称：" + task.getName());
				System.out.println("执行对象id:" + task.getExecutionId());
				System.out.println("start:" + task.getStartTime());
				System.out.println("end:" + task.getEndTime());

				System.out.println("dur:" + task.getDurationInMillis());
			}
		}
	}

	// 查询历史流程
	public void queryHistoryProcess() {
		// 历史任务办理人
		String taskAssignee = "gonzo";
		// 获取流程引擎对象
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		// 使用办理人查询流程实例
		List<HistoricProcessInstance> list = processEngine.getHistoryService()
				.createHistoricProcessInstanceQuery()
				.processInstanceId("43749").list();
		if (list != null && list.size() > 0) {
			for (HistoricProcessInstance process : list) {
				System.out.println("================");
				System.out.println("流程id：" + process.getId());
				System.out.println("发起人：" + process.getStartUserId());
				// System.out.println("任务办理人："+process.get);
				System.out.println("任务名称：" + process.getName());
				System.out.println("start:" + process.getStartTime());
				System.out.println("end:" + process.getEndTime());

				System.out.println("dur:" + process.getDurationInMillis());
			}
		}
	}

	// 查询历史流程
	public void queryHistoryProcessDetail() {
		// 历史任务办理人
		String taskAssignee = "gonzo";
		// 获取流程引擎对象
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		// 使用办理人查询流程实例
		List<HistoricActivityInstance> list = processEngine.getHistoryService()
				.createHistoricActivityInstanceQuery()
				.processInstanceId("43749").list();
		if (list != null && list.size() > 0) {
			for (HistoricActivityInstance process : list) {
				System.out.println("================");
				System.out.println("流程id：" + process.getId());
				System.out.println("办理人：" + process.getAssignee());
				System.out.println("任务名称：" + process.getActivityName());
				System.out.println("start:" + process.getStartTime());
				System.out.println("end:" + process.getEndTime());

				System.out.println("dur:" + process.getDurationInMillis());
			}
		}
	}

	public void queryFormMsg() {
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		String taskId = "111033";
		TaskFormData td = processEngine.getFormService()
				.getTaskFormData(taskId);
		List<FormProperty> pros = td.getFormProperties();
		for (FormProperty tmp : pros) {
			System.out.println("pid:" + tmp.getId());
			System.out.println("pname:" + tmp.getName());
			System.out.println("pvalue:" + tmp.getValue());
			System.out.println("ptype:" + tmp.getType().getName());
			System.out.println("=========");
		}
	}
	
//	@Test
	public void queryVarsMsg() {
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		String processInstanceId = "115906";
		String taskId = "115920";
		Map<String, Object> taskMaps = processEngine.getTaskService().getVariables(taskId );
		String t = taskMaps.get("test.test2")+"";
		 System.out.println("key= test.test2 value="+t);  
		Iterator it = taskMaps.entrySet().iterator();  
		  while (it.hasNext()) {  
		   Map.Entry entry = (Map.Entry) it.next();  
		   Object key = entry.getKey();  
		   Object value = entry.getValue();  
		   System.out.println("key=" + key + " value=" + value);  
		}
		  System.out.println("==================");  
		ProcessInstance inst = processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
		Map<String, Object> maps = inst.getProcessVariables();
		Iterator mit = maps.entrySet().iterator();  
		  while (mit.hasNext()) {  
		   Map.Entry entry = (Map.Entry) mit.next();  
		   Object key = entry.getKey();  
		   Object value = entry.getValue();  
		   System.out.println("key=" + key + " value=" + value);  
		}
	}

}
